package redis

import (
	"fmt"
	"log"
	"strconv"
)

const PrefixGoods = "goods_stock:goods_id_"

// 添加商品虚拟库存 increment goods virtual stock
func IncrGoodsStock(goodsId, stock int64) error {

	for i := 0; i < int(stock); i++ {
		err = RedisClient.RPush(PrefixGoods+strconv.Itoa(int(goodsId)), goodsId).Err()
		if err != nil {
			fmt.Println("添加商品虚拟库存失败")
			return err
		}
	}
	return nil
}

// 获取商品虚拟库存 get goods virtual stock
func GetGoodsStock(goodsId int64) (int64, error) {
	stock, err := RedisClient.LLen(PrefixGoods + strconv.Itoa(int(goodsId))).Result()
	if err != nil {
		//fmt.Println("获取商品虚拟库存失败：", err)
		log.Println("获取商品虚拟库存失败：", err)
		return 0, err
	}
	return stock, nil
}

// 移除商品虚拟库存 remove goods virtual stock
func RemoveGoodsStock(goodsId, stock int64) error {
	for i := 0; i < int(stock); i++ {
		err = RedisClient.LPop(PrefixGoods + strconv.Itoa(int(goodsId))).Err()
		if err != nil {
			fmt.Println("移除商品虚拟库存失败")
			return err
		}
	}
	return nil
}
